import router from '@/router';
import { constantRoutes, asyncRoutes } from '@/router';
import { storeToRefs } from 'pinia';
import useUserInfo from '@/stores/userInfo';
import useRoleRouter from '@/stores/roleRouter';
import type { IRoleNavMenu } from '@/stores/roleRouter/type';
import type { ISetFilterHasRolesRoutes, IHasRoles, IFormatFlatteningRoutes, ISetAddRoute } from './type';

/**
 * @description: 判断路由 name 中是否包含当前登录用户权限字段
 * @param {RouteRecordRaw} route 当前循环时的路由项
 * @param {string} roles 用户权限标识，在 userInfo（用户信息）的 roles 数组
 * @return {*} 返回对比后有权限的路由项
 */
const hasRoles: IHasRoles = (route, roles) => {
	return roles.some(role => route.name === role);
};

/**
 * @description: 动态路由+静态路由 处理成为菜单需要的格式
 * @param {RouteRecordRaw} routes 动态路由+静态路由
 * @return {*} 处理后的菜单数组
 */
const formatFlatteningRoutes: IFormatFlatteningRoutes = routes => {
	const navMenu: IRoleNavMenu[] = [];
	routes.map(route => {
		const item: any = { ...route };
		// 隐藏菜单
		if (item.meta?.isHide) return;
		// 若是有子元素
		if (item.children) item.children = formatFlatteningRoutes(item.children);
		const menu: IRoleNavMenu = {
			name: item.meta.title,
			icon: item.meta.icon,
			index: item.meta.index,
			children: item.children || [],
		};
		navMenu.push(menu);
	});
	return navMenu;
};

/**
 * @description: 添加动态路由
 * @param {string} routes 拥有的权限路由
 */
const setAddRoute: ISetAddRoute = routes => {
	routes.forEach(route => {
		router.addRoute(route);
	});
};

/**
 * @description: 获取当前用户权限标识去比对路由表，设置递归过滤有权限的路由
 * @param {RouteRecordRaw} routes 当前动态路由
 * @param {string} roles 用户权限标识，在 userInfos（用户信息）的 roles 数组
 * @return {*} 返回有权限的路由数组
 */
const setFilterHasRolesRoutes: ISetFilterHasRolesRoutes = (routes, roles) => {
	// 有权限的路由数组
	const newRouter: any[] = [];
	routes.map(route => {
		const item: any = { ...route };
		// 判断该路由是否有权限
		if (!hasRoles(item, roles)) return;
		// 若是有子路由
		if (item.children) item.children = setFilterHasRolesRoutes(item.children, roles);
		newRouter.push(item);
	});
	return newRouter;
};

/**
 * @description: 初始化方法，防止刷新时路由丢失
 * @return {*}  无返回值
 */
const initFrontEndControlRoutes = () => {
	// 获取登录的用户信息
	const stores = useUserInfo();
	const roleStores = useRoleRouter();
	const { userInfo } = storeToRefs(stores);
	const { roleNavMenu } = storeToRefs(roleStores);
	if (!userInfo.value?.rolePages?.length) return (roleNavMenu.value = formatFlatteningRoutes(constantRoutes));
	// 获取有权限的路由数组
	const rolesRouter = setFilterHasRolesRoutes(asyncRoutes, userInfo.value?.rolePages);
	// 注册权限路由
	setAddRoute(rolesRouter);
	// 用户所有拥有权限路由
	roleNavMenu.value = formatFlatteningRoutes([...constantRoutes, ...rolesRouter]);
};
export { initFrontEndControlRoutes };
